package vip.liux.register;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@SpringBootApplication
@EnableEurekaServer
@EnableWebSecurity
public class RegisterApplication {

    public static void main(String[] args) {
        SpringApplication.run(RegisterApplication.class, args);
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        // 关闭csrf
        http.csrf(AbstractHttpConfigurer::disable);
        http.httpBasic(Customizer.withDefaults());
        http.authorizeHttpRequests(c -> c.anyRequest().authenticated());
        return http.build();
    }

    @Bean
    public UserDetailsService userDetailsService(RegisterUserProperties registerUserProperties) {
        List<UserDetails> users = registerUserProperties.getUsers().stream()
                .map(u -> User.withUsername(u.username())
                        .password("{noop}" + u.password())
                        .roles(u.roles().split(","))
                        .build())
                .collect(Collectors.toList());
        return new InMemoryUserDetailsManager(users);
    }

    @Component
    @ConfigurationProperties(prefix = "register")
    public static class RegisterUserProperties {
        private List<UserConfig> users;

        public List<UserConfig> getUsers() {
            return users;
        }

        public void setUsers(List<UserConfig> users) {
            this.users = users;
        }

        public record UserConfig(String username, String password, String roles) {
        }
    }
}
